package net.awpspace.mobile.global;

import java.io.IOException;
import java.util.Vector;

import javax.microedition.lcdui.Image;

import net.awpspace.mobile.management.book.BookModel;

import com.sun.lwuit.Dialog;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.plaf.Border;

/**
 * Application ultilities
 * 
 * @author Diep
 * 
 */
public class Utils {

	/**
	 * Image names
	 */
	public static final String ICON_BOOK_LIST = "/book/icon_book_list.png";
	public static final String ICON_BOOK_DELETE = "/book/icon_book_delete.png";
	public static final String ICON_BOOK_INSERT = "/book/icon_book_insert.png";

	/**
	 * Singleton
	 */
	private static Utils instance;

	private Dialog dialog;
	private TextArea textArea;

	private Utils() {
		textArea = new TextArea();
		textArea.setFocusable(false);
		textArea.setScrollVisible(false);
		textArea.getStyle().setBorder(Border.createEmpty());
		textArea.getStyle().setFgColor(0xffffff);
		textArea.setEditable(false);
		textArea.setRows(25);
		dialog = new Dialog("Alert");
		dialog.setScrollable(false);
		dialog.setLayout(new BorderLayout());
		dialog.addComponent(BorderLayout.CENTER, textArea);
	}

	public static Utils getInstance() {
		if (instance == null) {
			instance = new Utils();
		}
		return instance;
	}

	/**
	 * Temporary
	 * 
	 * @return
	 */
	public static Vector generateBooks() {
		Vector books = new Vector();
		for (int i = 0; i < 10; ++i) {
			books.addElement(new BookModel(i, "Hello " + i, "Luceefer",
					"http://www.developer.nokia.com/images/l/logo.png",
					"Đây là siêu sách thứ " + i));
		}
		return books;
	}

	/**
	 * Image loader
	 * 
	 * @param file
	 * @return
	 */
	public static Image load(String file) {
		Image image = null;
		try {
			image = Image.createImage(file);
		} catch (NullPointerException npe) {
			System.err.println("No image file name specified");
		} catch (IOException ioe) {
			System.err.println("Image not found or invalid: " + file);
		}
		return image;
	}

	/**
	 * Alert info to user
	 * 
	 * @param info
	 */
	public void alert(String info) {
		alert(info, Global.ALERT_TIMEOUT);
	}

	/**
	 * Alert info to user with timeout
	 * 
	 * @param info
	 * @param timeout
	 */
	public void alert(String info, int timeout) {
		textArea.setText(info);
		dialog.setTimeout(timeout * 1000);
		dialog.show(0, 100, 10, 10, true);
	}
}
